package com.szeastroc.manage.config;

import java.io.IOException;

import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.WebAppResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;

@Configuration
public class BeetlConf  {

	String templatesPath = "templates/";//模板跟目录 ，比如 "templates"
	String templatesPath2 = "WEB-INF/views/";//模板跟目录 ，比如 "templates"

	@Bean(initMethod = "init", name = "beetlConfig")
	public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
		BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
		//获取Spring Boot 的ClassLoader
		/*ClassLoader loader = Thread.currentThread().getContextClassLoader();
		if(loader==null){
			loader = BeetlConf.class.getClassLoader();
		}
		//beetlGroupUtilConfiguration.setConfigProperties(extProperties);//额外的配置，可以覆盖默认配置，一般不需要
		ClasspathResourceLoader cploder = new ClasspathResourceLoader(BeetlConf.class.getClassLoader(),
		        templatesPath);
		beetlGroupUtilConfiguration.setResourceLoader(cploder);
		beetlGroupUtilConfiguration.init();
		//如果使用了优化编译器，涉及到字节码操作，需要添加ClassLoader
		beetlGroupUtilConfiguration.getGroupTemplate().setClassLoader(loader);*/
		
		ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
        try {
            // WebAppResourceLoader 配置root路径是关键
            WebAppResourceLoader webAppResourceLoader =
                    new WebAppResourceLoader(patternResolver.getResource("classpath:/").getFile().getPath());
            beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
        } catch (IOException e) {
            e.printStackTrace();
        }
		return beetlGroupUtilConfiguration;

	}

	 @Bean(name = "beetlViewResolver")
	    public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
	        BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
	        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
	        beetlSpringViewResolver.setOrder(0);
	        beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
	        return beetlSpringViewResolver;
	    }
}
